package org.example.topics;

import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;

/**
 * <p>
 *
 * </p>
 *
 * @author 12071
 * @date 2022/8/17 11:36
 */
public class ReceiveTopic1 {
    private static final String EXCHANGE_NAME = "topic_logs";
    private static final String[]  pattern = new String[]{"aa.*", "one.#"};

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
        String queueName = channel.queueDeclare().getQueue();

        System.out.println(" [*] pattern: "+ Arrays.toString(pattern));
        for (String bindingKey : pattern) {
            channel.queueBind(queueName, EXCHANGE_NAME, bindingKey);
        }

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" +
                    delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };
        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { });
    }
}
